package com.jblv.frame.common.es.service.impl;

import com.jblv.frame.common.dto.PageResult;
import com.jblv.frame.common.es.base.ESBaseEntity;
import com.jblv.frame.common.es.param.SearchParam;
import com.jblv.frame.common.es.service.IESBaseService;
import com.jblv.frame.common.es.util.ESUtils;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ESIndexService
 * @projectName jblv-frame
 * @packageName com.jblv.common.es.service.impl
 * @description es
 * @date Create at 2020/4/29 17:31
 * @since jdk1.8
 */
public class ESBaseService<T extends ESBaseEntity> implements IESBaseService<T> {
    private static final String LASTDATE_FIELD = "updateTime";
    private Class<T> clazz = null;
    private static Logger logger = LoggerFactory.getLogger(ESBaseService.class);
    @Autowired
    protected JestClient jestClient;

    public ESBaseService() {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType)type;
            Type claz = pType.getActualTypeArguments()[0];
            if (claz instanceof Class) {
                this.clazz = (Class)claz;
            }
        }

    }

    @Override
    public String save(T entity) {
        try {
            ESBaseEntity eSBaseEntity = this.clazz.newInstance();
            String indexName = eSBaseEntity.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            }
            String type = eSBaseEntity.getType();
            if (StringUtils.isEmpty(type)) {
                return null;
            }
            Index.Builder builder = new Index.Builder(entity);
            String id = entity.getId();
            if (StringUtils.isNotEmpty(id)) {
                builder.id(id);
            }
            Index index =builder.index(indexName).type(type).build();
            DocumentResult result = null;
            try {
                result = this.jestClient.execute(index);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (result == null) {
                return null;
            }
            return result.getId();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public String save(T entity, boolean refresh) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else {
                    Index.Builder builder = new Index.Builder(entity);
                    String id = entity.getId();
                    if (StringUtils.isNotEmpty(id)) {
                        builder.id(id);
                    }

                    Index index = builder.index(indexName).refresh(refresh).type(type).build();
                    DocumentResult result = null;

                    try {
                        result = this.jestClient.execute(index);
                    } catch (IOException var11) {
                        var11.printStackTrace();
                    }

                    return result == null ? null : result.getId();
                }
            }
        } catch (Exception var12) {
            logger.error(var12.getMessage());
            return null;
        }
    }

    @Override
    public void bulkSave(List<T> list) {
        try {
            if (list == null || list.isEmpty() || list.size() <= 0) {
                return;
            }

            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return;
            }

            String type = t.getType();
            if (StringUtils.isEmpty(type)) {
                return;
            }

            io.searchbox.core.Bulk.Builder bulk = new io.searchbox.core.Bulk.Builder();
            int count = 0;
            Iterator var7 = list.iterator();

            while(var7.hasNext()) {
                T entity = (T) var7.next();
                if (entity != null) {
                    Index.Builder builder = new Index.Builder(entity);
                    String id = entity.getId();
                    if (StringUtils.isNotEmpty(id)) {
                        builder.id(id);
                    }

                    Index index = builder.index(indexName).type(type).build();
                    bulk.addAction(index);
                    ++count;
                }
            }

            if (count <= 0) {
                return;
            }

            this.jestClient.execute(bulk.build());
        } catch (Exception var12) {
            logger.error(var12.getMessage());
        }

    }

    @Override
    public String updateById(T entity) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = this.clazz.newInstance().getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else {
                    String id = entity.getId();
                    if (StringUtils.isEmpty(id)) {
                        return null;
                    } else {
                        Index index = new Index.Builder(entity).id(id).index(indexName).type(type).build();
                        DocumentResult result = null;

                        try {
                            result = this.jestClient.execute(index);
                        } catch (IOException var9) {
                            var9.printStackTrace();
                        }

                        return result == null ? null : result.getId();
                    }
                }
            }
        } catch (Exception var10) {
            logger.error(var10.getMessage());
            return null;
        }
    }

    @Override
    public String updateById(T entity, boolean reFresh) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = this.clazz.newInstance().getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else {
                    String id = entity.getId();
                    if (StringUtils.isEmpty(id)) {
                        return null;
                    } else {
                        Index index = new Index.Builder(entity).refresh(reFresh).id(id).index(indexName).type(type).build();
                        DocumentResult result = null;

                        try {
                            result = this.jestClient.execute(index);
                        } catch (IOException var10) {
                            var10.printStackTrace();
                        }

                        return result == null ? null : result.getId();
                    }
                }
            }
        } catch (Exception var11) {
            logger.error(var11.getMessage());
            return null;
        }
    }

    @Override
    public String update(T entity) {
        return null;
    }

    @Override
    public Boolean deleteById(String id) {
        return this.deleteById(id, false);
    }

    @Override
    public Boolean deleteById(String id, boolean refresh) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return false;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return false;
                } else {
                    Delete delete = new io.searchbox.core.Delete.Builder(id).index(indexName).refresh(refresh).type(type).build();
                    DocumentResult result = null;

                    try {
                        result = this.jestClient.execute(delete);
                    } catch (IOException var9) {
                        var9.printStackTrace();
                    }

                    return result == null ? false : true;
                }
            }
        } catch (Exception var10) {
            logger.error(var10.getMessage());
            return false;
        }
    }

    @Override
    public Integer deleteByQuery(String params) {
        return 0;
    }

    @Override
    public T getById(String id) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else {
                    Get get = new io.searchbox.core.Get.Builder(indexName, id).type(type).build();
                    ESBaseEntity result = null;

                    try {
                        JestResult jestResult = this.jestClient.execute(get);
                        result = jestResult.getSourceAsObject(this.clazz);
                    } catch (IOException var9) {
                        var9.printStackTrace();
                    }

                    return (T)result;
                }
            }
        } catch (Exception var10) {
            logger.error(var10.getMessage());
            return null;
        }
    }

    @Override
    public List<T> searchAll() {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                searchSourceBuilder.query(QueryBuilders.matchAllQuery());
                Search search = new io.searchbox.core.Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).build();
                SearchResult result = this.jestClient.execute(search);
                List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                List<T> list = new ArrayList();
                if (hits != null && !hits.isEmpty()) {
                    list = hits.stream().map((h) -> {
                        return h.source;
                    }).collect(Collectors.toList());
                }

                return list;
            }
        } catch (Exception var8) {
            logger.error(var8.getMessage());
            return null;
        }
    }

    @Override
    public PageResult<T> search(List<String> fields, Set<SearchParam> searchParams, Map<String, Boolean> sortParams, List<String> highLight, Integer pageSize, Integer pageNum) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else if (searchParams != null && searchParams.size() != 0) {
                    if (pageSize == null || pageSize <= 0) {
                        pageSize = 10;
                    }

                    if (pageNum == null || pageNum <= 0) {
                        pageNum = 1;
                    }

                    int from = (pageNum - 1) * pageSize;
                    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                    searchSourceBuilder.from(from);
                    searchSourceBuilder.size(pageSize);
                    BoolQueryBuilder boolQueryBuilder = this.createBoolQueryBuilder(searchParams);
                    if (boolQueryBuilder == null) {
                        return null;
                    } else {
                        searchSourceBuilder.query(boolQueryBuilder);
                        this.createSortParams(sortParams, searchSourceBuilder);
                        boolean needHighLight = this.createHighLight(highLight, searchSourceBuilder, t);
                        if (fields != null && !fields.isEmpty()) {
                            searchSourceBuilder.fetchSource((String[])fields.toArray(new String[0]), (String[])null);
                        }

                        Search search = (((new io.searchbox.core.Search.Builder(searchSourceBuilder.toString())).addIndex(indexName)).addType(type)).build();
                        PageResult<T> pageResult = new PageResult();
                        pageResult.setCurPage(pageNum);
                        pageResult.setPageSize(pageSize);
                        SearchResult result = this.jestClient.execute(search);
                        pageResult.setTotal(Integer.parseInt(result.getTotal().toString()));
                        List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                        List<T> resultList = this.getResultList(highLight, needHighLight, hits);
                        pageResult.setList(resultList);
                        return pageResult;
                    }
                } else {
                    return null;
                }
            }
        } catch (Exception var19) {
            logger.error(var19.getMessage());
            return null;
        }
    }

    @Override
    public List<T> search(List<String> fields, Set<SearchParam> searchParams, Map<String, Boolean> sortParams, List<String> highLight, Integer pageSize, Long lastdate) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else if (searchParams != null && searchParams.size() != 0) {
                    if (pageSize == null || pageSize <= 0) {
                        pageSize = 10;
                    }

                    if (lastdate == null || lastdate <= 0L) {
                        lastdate = 0L;
                    }

                    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                    searchSourceBuilder.size(pageSize);
                    BoolQueryBuilder boolQueryBuilder = this.createBoolQueryBuilder(searchParams);
                    if (boolQueryBuilder == null) {
                        return null;
                    } else {
                        searchSourceBuilder.query(boolQueryBuilder);
                        this.createSortParams(sortParams, searchSourceBuilder);
                        boolean needHighLight = this.createHighLight(highLight, searchSourceBuilder, t);
                        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("updateTime");
                        if (lastdate != 0L) {
                            rangeQueryBuilder.lt(lastdate);
                        }

                        boolQueryBuilder.must(rangeQueryBuilder);
                        if (fields != null && !fields.isEmpty()) {
                            searchSourceBuilder.fetchSource(fields.toArray(new String[0]), null);
                        }

                        Search search = new io.searchbox.core.Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(type).build();
                        SearchResult result = this.jestClient.execute(search);
                        List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                        List<T> resultList = this.getResultList(highLight, needHighLight, hits);
                        return resultList;
                    }
                } else {
                    return null;
                }
            }
        } catch (Exception var18) {
            logger.error(var18.getMessage());
            return null;
        }
    }

    @Override
    public T selectOne(Map<String, Object> searchParams) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else if (searchParams == null || searchParams.size() == 0) {
                    return null;
                } else {
                    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                    BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
                    boolean hasSearchKey = false;
                    Iterator var8 = searchParams.entrySet().iterator();

                    while(true) {
                        String key;
                        Object value;
                        String searchValue;
                        do {
                            Field field;
                            while(true) {
                                do {
                                    if (!var8.hasNext()) {
                                        if (!hasSearchKey) {
                                            return null;
                                        }

                                        searchSourceBuilder.query(boolBuilder);
                                        Search search = new io.searchbox.core.Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(type).build();
                                        SearchResult result = this.jestClient.execute(search);
                                        List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                                        if (hits != null && !hits.isEmpty()) {
                                            SearchResult.Hit<T, Void> hit = hits.get(0);
                                            T source = hit.source;
                                            return source;
                                        }

                                        return null;
                                    }

                                    Map.Entry<String, Object> entry = (Map.Entry)var8.next();
                                    key = entry.getKey();
                                    value = entry.getValue();
                                } while(value == null);

                                try {
                                    field = this.clazz.getDeclaredField(key);
                                    break;
                                } catch (NoSuchFieldException var15) {
                                }
                            }

                            Class<?> fieldType = field.getType();
                            if (!fieldType.equals(String.class)) {
                                break;
                            }

                            searchValue = ESUtils.escapeQueryChars(value.toString());
                        } while(searchValue.trim().isEmpty());

                        hasSearchKey = true;
                        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key, value);
                        boolBuilder.must(termQueryBuilder);
                    }
                }
            }
        } catch (Exception var16) {
            return null;
        }
    }

    protected boolean createHighLight(List<String> highLight, SearchSourceBuilder searchSourceBuilder, T t) {
        boolean needHighLight = false;
        if (highLight != null && !highLight.isEmpty()) {
            Iterator var5 = highLight.iterator();

            while(var5.hasNext()) {
                String highLightField = (String)var5.next();

                try {
                    this.clazz.getDeclaredField(highLightField);
                } catch (NoSuchFieldException var8) {
                    continue;
                }

                HighlightBuilder highlightBuilder = searchSourceBuilder.highlighter();
                highlightBuilder.field(highLightField);
                highlightBuilder.preTags(new String[]{t.getPreTags()}).postTags(new String[]{t.getPostTags()});
                highlightBuilder.fragmentSize(500);
                needHighLight = true;
            }
        }

        return needHighLight;
    }

    protected void createSortParams(Map<String, Boolean> sortParams, SearchSourceBuilder searchSourceBuilder) {
        if (searchSourceBuilder != null) {
            String key;
            Boolean value;
            if (sortParams != null && sortParams.size() > 0) {
                for(Iterator var3 = sortParams.entrySet().iterator(); var3.hasNext(); searchSourceBuilder.sort(key, value ? SortOrder.ASC : SortOrder.DESC)) {
                    Map.Entry<String, Boolean> entry = (Map.Entry)var3.next();
                    key = (String)entry.getKey();
                    value = (Boolean)entry.getValue();
                    if (value == null) {
                        value = true;
                    }
                }
            }

        }
    }

    protected BoolQueryBuilder createBoolQueryBuilder(Set<SearchParam> searchParams) {
        if (searchParams != null && searchParams.size() != 0) {
            BoolQueryBuilder mustBoolBuilder = QueryBuilders.boolQuery();
            BoolQueryBuilder shouldBoolBuilder = QueryBuilders.boolQuery();
            boolean hasMust = false;
            boolean hasShould = false;
            Iterator var6 = searchParams.iterator();

            while(true) {
                while(true) {
                    String key;
                    Object value;
                    boolean should;
                    Field field;
                    while(true) {
                        do {
                            if (!var6.hasNext()) {
                                if (!hasMust && !hasShould) {
                                    return null;
                                }

                                BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
                                if (hasMust) {
                                    boolBuilder.must(mustBoolBuilder);
                                }

                                if (hasShould) {
                                    boolBuilder.must(shouldBoolBuilder);
                                }

                                return boolBuilder;
                            }

                            SearchParam param = (SearchParam)var6.next();
                            key = param.getKey();
                            value = param.getValue();
                            should = param.isShould();
                        } while(value == null);

                        try {
                            field = this.clazz.getDeclaredField(key);
                            break;
                        } catch (NoSuchFieldException var15) {
                        }
                    }

                    Class<?> fieldType = field.getType();
                    if (fieldType.equals(String.class)) {
                        String searchValue = ESUtils.escapeQueryChars(value.toString());
                        if (!searchValue.trim().isEmpty()) {
                            WildcardQueryBuilder itemBoolBuilder = QueryBuilders.wildcardQuery(ESUtils.warpKeyword(key), ESUtils.warpWildcard(searchValue));
                            if (should) {
                                shouldBoolBuilder.should(itemBoolBuilder);
                                hasShould = true;
                            } else {
                                mustBoolBuilder.must(itemBoolBuilder);
                                hasMust = true;
                            }
                        }
                    } else if (fieldType.equals(Integer.class) || fieldType.equals(Long.class) || fieldType.equals(Double.class) || fieldType.equals(Float.class)) {
                        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key, value);
                        if (should) {
                            shouldBoolBuilder.should(termQueryBuilder);
                            hasShould = true;
                        } else {
                            mustBoolBuilder.must(termQueryBuilder);
                            hasMust = true;
                        }
                    }
                }
            }
        } else {
            return null;
        }
    }

    protected List<T> getResultList(List<String> highLight, boolean needHighLight, List<SearchResult.Hit<T, Void>> hits) throws NoSuchFieldException, IllegalAccessException {
        if (hits != null && !hits.isEmpty()) {
            List<T> tList = new ArrayList<>();
            for (SearchResult.Hit<T, Void> hit : hits) {
                ESBaseEntity eSBaseEntity = (ESBaseEntity)hit.source;
                tList.add((T)eSBaseEntity);
                if (needHighLight) {
                    Map<String, List<String>> highlight = hit.highlight;
                    if (highlight != null)
                        for (String highLightField : highLight) {
                            List<String> values = highlight.get(highLightField);
                            if (values != null && !values.isEmpty()) {
                                Field field = this.clazz.getDeclaredField(highLightField);
                                field.setAccessible(true);
                                field.set(eSBaseEntity, values.get(0));
                            }
                        }
                }
            }
            return tList;
        }
        return null;
    }

    @Override
    public PageResult<T> searchByLocation(List<String> fields, Set<SearchParam> searchParams, Map<String, Boolean> sortParams, List<String> highLight, Integer pageSize, Integer pageNum, String nowLocation, String filterDistance) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else if (searchParams != null && searchParams.size() != 0) {
                    if (pageSize == null || pageSize <= 0) {
                        pageSize = 10;
                    }

                    if (pageNum == null || pageNum <= 0) {
                        pageNum = 1;
                    }

                    int from = (pageNum - 1) * pageSize;
                    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                    searchSourceBuilder.from(from);
                    searchSourceBuilder.size(pageSize);
                    BoolQueryBuilder boolQueryBuilder = this.createBoolQueryBuilder(searchParams);
                    if (boolQueryBuilder == null) {
                        return null;
                    } else {
                        searchSourceBuilder.query(boolQueryBuilder);
                        if (StringUtils.isEmpty(nowLocation)) {
                            this.createSortParams(sortParams, searchSourceBuilder);
                        }

                        boolean needHighLight = this.createHighLight(highLight, searchSourceBuilder, t);
                        if (fields != null && !fields.isEmpty()) {
                            searchSourceBuilder.fetchSource((String[])fields.toArray(new String[0]), (String[])null);
                        }

                        if (StringUtils.isNotEmpty(nowLocation)) {
                            double lat = 0.0D;
                            double lon = 0.0D;
                            String[] latAndLon = nowLocation.split(",");
                            if (latAndLon.length == 2) {
                                lat = Double.parseDouble(latAndLon[0]);
                                lon = Double.parseDouble(latAndLon[1]);
                            }

                            GeoDistanceQueryBuilder builder = QueryBuilders.geoDistanceQuery("latlon").distance(Double.parseDouble(filterDistance), DistanceUnit.KILOMETERS).point(lat, lon).geoDistance(GeoDistance.ARC);
                            GeoDistanceSortBuilder sortBuilder = ((GeoDistanceSortBuilder)SortBuilders.geoDistanceSort("latlon", lat, lon).unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC)).geoDistance(GeoDistance.ARC);
                            searchSourceBuilder.postFilter(builder).sort(sortBuilder);
                        }

                        Search search = (((new io.searchbox.core.Search.Builder(searchSourceBuilder.toString())).addIndex(indexName)).addType(type)).build();
                        PageResult<T> pageResult = new PageResult();
                        pageResult.setCurPage(pageNum);
                        pageResult.setPageSize(pageSize);
                        SearchResult result = this.jestClient.execute(search);
                        pageResult.setTotal(Integer.parseInt(result.getTotal().toString()));
                        List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                        List<T> resultList = this.getList(highLight, needHighLight, hits);
                        pageResult.setList(resultList);
                        return pageResult;
                    }
                } else {
                    return null;
                }
            }
        } catch (Exception var23) {
            logger.error(var23.getMessage());
            return null;
        }
    }

    protected List<T> getList(List<String> highLight, boolean needHighLight, List<SearchResult.Hit<T, Void>> hits) throws NoSuchFieldException, IllegalAccessException {
        if (hits != null && !hits.isEmpty()) {
            List<T> tList = new ArrayList<>();
            for (SearchResult.Hit<T, Void> hit : hits) {
                ESBaseEntity eSBaseEntity = (ESBaseEntity)hit.source;
                List<String> sortList = hit.sort;
                for (String sort : sortList) {
                    if (sort.contains(".")) {
                        eSBaseEntity.setDist(Double.valueOf(Double.parseDouble(sort)));
                        break;
                    }
                }
                tList.add((T)eSBaseEntity);
                if (needHighLight) {
                    Map<String, List<String>> highlight = hit.highlight;
                    if (highlight != null)
                        for (String highLightField : highLight) {
                            List<String> values = highlight.get(highLightField);
                            if (values != null && !values.isEmpty()) {
                                Field field = this.clazz.getDeclaredField(highLightField);
                                field.setAccessible(true);
                                field.set(eSBaseEntity, values.get(0));
                            }
                        }
                }
            }
            return tList;
        }
        return null;
    }

    @Override
    public PageResult<T> searchByTerms(List<String> fields, Set<SearchParam> searchParams, Map<String, Boolean> sortParams, List<String> highLight, Integer pageSize, Integer pageNum, Map<String, List<String>> termsParams) {
        try {
            ESBaseEntity eSBaseEntity = (ESBaseEntity)this.clazz.newInstance();
            String indexName = eSBaseEntity.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            }
            String type = eSBaseEntity.getType();
            if (StringUtils.isEmpty(type)) {
                return null;
            }
            if (searchParams == null || searchParams.size() == 0) {
                return null;
            }
            if (pageSize == null || pageSize.intValue() <= 0) {
                pageSize = Integer.valueOf(10);
            }
            if (pageNum == null || pageNum.intValue() <= 0) {
                pageNum = Integer.valueOf(1);
            }
            int from = (pageNum.intValue() - 1) * pageSize.intValue();
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.from(from);
            searchSourceBuilder.size(pageSize.intValue());
            BoolQueryBuilder boolQueryBuilder = createBoolQueryBuilder(searchParams);
            for (Map.Entry<String, List<String>> entry : termsParams.entrySet()) {
                String key = entry.getKey();
                List<String> termsList = entry.getValue();
                boolQueryBuilder.must((QueryBuilder)QueryBuilders.termsQuery(key, termsList));
            }
            if (boolQueryBuilder == null) {
                return null;
            }
            searchSourceBuilder.query((QueryBuilder)boolQueryBuilder);
            createSortParams(sortParams, searchSourceBuilder);
            boolean needHighLight = createHighLight(highLight, searchSourceBuilder, (T)eSBaseEntity);
            if (fields != null && !fields.isEmpty()) {
                searchSourceBuilder.fetchSource(fields.<String>toArray(new String[0]), null);
            }
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(type).build();
            PageResult<T> pageResult = new PageResult();
            pageResult.setCurPage(pageNum.intValue());
            pageResult.setPageSize(pageSize.intValue());
            SearchResult result = this.jestClient.execute(search);
            pageResult.setTotal(Integer.parseInt(result.getTotal().toString()));
            List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
            List<T> resultList = getResultList(highLight, needHighLight, hits);
            pageResult.setList(resultList);
            return pageResult;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public List<T> searchByTermsForApp(List<String> fields, Set<SearchParam> searchParams, Map<String, Boolean> sortParams, List<String> highLight, Integer pageSize, Long lastdate, Map<String, List<String>> termsParams) {
        try {
            T t = this.clazz.newInstance();
            String indexName = t.getIndexName();
            if (StringUtils.isEmpty(indexName)) {
                return null;
            } else {
                String type = t.getType();
                if (StringUtils.isEmpty(type)) {
                    return null;
                } else if (searchParams != null && searchParams.size() != 0) {
                    if (pageSize == null || pageSize <= 0) {
                        pageSize = 10;
                    }

                    if (lastdate == null || lastdate <= 0L) {
                        lastdate = 0L;
                    }

                    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                    searchSourceBuilder.size(pageSize);
                    BoolQueryBuilder boolQueryBuilder = this.createBoolQueryBuilder(searchParams);
                    Iterator var13 = termsParams.entrySet().iterator();

                    while(var13.hasNext()) {
                        Map.Entry<String, List<String>> entry = (Map.Entry)var13.next();
                        String key = (String)entry.getKey();
                        List<String> termsList = entry.getValue();
                        boolQueryBuilder.must(QueryBuilders.termsQuery(key, termsList));
                    }

                    if (boolQueryBuilder == null) {
                        return null;
                    } else {
                        searchSourceBuilder.query(boolQueryBuilder);
                        this.createSortParams(sortParams, searchSourceBuilder);
                        boolean needHighLight = this.createHighLight(highLight, searchSourceBuilder, t);
                        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("updateTime");
                        if (lastdate != 0L) {
                            rangeQueryBuilder.lt(lastdate);
                        }

                        boolQueryBuilder.must(rangeQueryBuilder);
                        if (fields != null && !fields.isEmpty()) {
                            searchSourceBuilder.fetchSource((String[])fields.toArray(new String[0]), (String[])null);
                        }

                        Search search = (((new io.searchbox.core.Search.Builder(searchSourceBuilder.toString())).addIndex(indexName)).addType(type)).build();
                        SearchResult result = this.jestClient.execute(search);
                        List<SearchResult.Hit<T, Void>> hits = result.getHits(this.clazz);
                        List<T> resultList = this.getResultList(highLight, needHighLight, hits);
                        return resultList;
                    }
                } else {
                    return null;
                }
            }
        } catch (Exception var19) {
            logger.error(var19.getMessage());
            return null;
        }
    }
}
